import requests
import parsel
import re
import time
import json
import m3u8
from concurrent.futures import ThreadPoolExecutor,as_completed
from get_video import GetVideo
import os

from urllib.parse import urlparse, parse_qs

def get_single_page(pageNum):
    url = f"https://www.cupfox8.cc/foxplay/34546-1-{pageNum}.html"
    print(url)
    response = requests.get(url=url)
    selector1 = parsel.Selector(response.text)
    contents = selector1.css('body > div.page.player > div.main > div > div.module.module-player > div > div.player-box > div > script:nth-child(1)::text')
    # print(contents.get())
    # print(baseUrl + picUrl)
    # print(video_url)
    values = matchValue("var player_aaaa=((.+))", contents.get(), 1)
    datas = json.loads(values)
    print(datas)

    return datas

def build_content(datas):
    content = ''
    for data in datas:
        content += f"### {data[0]} \n 视频在线地址：[在线地址]({data[1]}) \n ![]({data[2]}) \n 播放地址：{data[3]}\n"
    return content

def batch_load(total_page):
    file_name = "./titiwo/titiwo{}.md"
    
    count = 5
    file_content = ''
    for i in range(total_page):
        if i > 200:
            file_content += build_content(get_single_page(pageNum=(i + 1)))
            print(f"第{i+1}页")
            if (i + 1) % 50 == 0 or total_page == i + 1:
                count += 1
                print(file_content)
                with open(file_name.format(count), 'a+', encoding='utf-8') as f:
                    f.write(file_content)
                    file_content = ''
            time.sleep(0.5) 
            
def batch_load_for_zhifou(total_page):
    datas = list()
    for i in range(total_page):
        vod_json = get_single_page(pageNum=(i + 1))
        datas.append((vod_json['link_next'], vod_json['url'], vod_json['url_next']))
        time.sleep(0.5) 
    return datas
        
    
def matchValue(reStr, sourceContent, matchIndex):
    pat = re.compile(reStr) #用()表示1个组，2个组
    m = pat.search(sourceContent)
    if m == None:
        return 
    return m.group(matchIndex) #默认为0，表示匹配整个字符串

def getTsFileInfo(url):
    response = requests.get(url=url)
    print(response.text)
    
def bach_download(base_dir):
    content = open("zhifou_m3u8.json", encoding="utf-8").read()
    json_data = json.loads(content)
    for i, data in enumerate(json_data):
        if i == 29:
            m3u8_url = get_m3u8_url(data[1])
            print(m3u8_url)
            download(m3u8_url, base_dir=base_dir, index=f'{i + 1}')


def download_by_path_url(m3u8_url, fileSavePath):
    m3u8_obj = m3u8.load(m3u8_url)
    total = len(m3u8_obj.segments)
    if not os.path.exists(fileSavePath):
        os.makedirs(fileSavePath)
    m3u8_obj = m3u8.load(m3u8_url)
    total = len(m3u8_obj.segments)
    with ThreadPoolExecutor(max_workers=20) as threadPool:
        futures = []
        for i, segment in enumerate(m3u8_obj.segments):
            segment_url = segment.absolute_uri
            futures.append(threadPool.submit(GetVideo.downloadOneFile, segment_url, fileSavePath, i, total))
          

        # 等待所有任务完成
        for future in as_completed(futures):
            try:
                future.result()  # 获取结果并捕获异常
            except Exception as e:
                print(f"Task failed with exception: {e}")
    
def download(m3u8_url, base_dir, index):
    fileSavePath = f'{base_dir}/{index}集'
    download_by_path_url(m3u8_url=m3u8_url, fileSavePath=fileSavePath)


def batch_merge_file(filePath):
    filePath = filePath.replace('\\', '/')
    file_list = os.listdir(filePath)
    print(file_list)
    filePath = filePath.replace('\\', '/')
    for f in file_list:
        GetVideo.fileMerge(filePath=f'{filePath}/{f}', exculd_index=[])
        
def batch_merge_file_ignore_no_exist_file(filePath):
    filePath = filePath.replace('\\', '/')
    file_list = os.listdir(filePath)
    print(file_list)
    for f in file_list:
        GetVideo.fileMergeIgnoreNoExistFile(filePath=f'{filePath}/{f}')
                
def get_m3u8_url(index_url, target_url='1000k/hls/mixed'):
    return index_url.replace('index', target_url)

def merge_mp4(filePath):
    file_list = os.listdir(filePath)
    filePath = filePath.replace('\\', '/')
    with open('%s.txt' % filePath, 'w+', encoding='utf-8') as f:
        content = ''
        for file in file_list:
            content += f"file '{filePath}/{file}'\n"
        f.write(content)


def download_from_file(list_file_path, file_base_dir):
    file_content = open(list_file_path, encoding='utf-8').read()
    lines = file_content.split('\n')
    for line in lines:
        data = line.split(',')
        print(data)
        m3u8_url = data[2]
        fileSavePath = f'{file_base_dir}/{data[1]}'
        download_single(m3u8_url, fileSavePath)
        
def get_jianlai_donghua():
    base_url = "https://kk20006.vip"
    url = f"{base_url}/vod/detail.html?cate_id=390&id=675015&type_id=4"
    response = requests.get(url=url)
    selector = parsel.Selector(response.text)
    # links = selector.css("#panel1 .active > div > .module-play-list-base > a::attr(href)")
    links = selector.css('.module > #panel1')
    link_content = links[0]
    link2 = link_content.css('div > .module-play-list-base > a::attr(href)')
    print(link2)
    # print(links)
    result_data = []
    for link in link2:
        url = link.get()
        print(url)
        # 解析URL查询部分
        query = urlparse(url).query
        params = parse_qs(query)

        # 获取line_id
        line_id = params.get('line_id', [None])[0]  # 使用get方法并提供默认值以防止键不存在时抛出异常
        print(line_id)
        openApiUrl = f"https://kk20006.vip/openapi/playline/{line_id}"
        response = requests.get(openApiUrl)
        result = response.json()
        print(result['info']['name'], result['info']['file'])
        result_data.append((result['info']['name'], result['info']['file']))
    open('./jianlai_donghua_m3u8.json', mode='w+', encoding="utf-8").write(json.dumps(result_data, ensure_ascii=False))
    return result_data

def down_load_jianlai():
    file_content = open('./jianlai_donghua_m3u8.json', encoding="utf-8").read()
    json_datas = json.loads(file_content)
    base_dir = 'D:/workspace/learning/python-learning/剑来'
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    # print(json_datas)
    # download_by_path_url(m3u8_url=m3u8_url, fileSavePath=fileSavePath)
    index = 0
    for json_data in json_datas:
        index += 1
        if index <= 26:
            continue
        m3u8_url = ''
        if index == 7:
            m3u8_url = 'https://c1.ddbbffcdn.com/video/jianlai/%E7%AC%AC07%E9%9B%86/index.m3u8'
        else:
            
            url_parse = urlparse(json_data[1])
            m3u8_base_url = url_parse.netloc
            scheme = url_parse.scheme
            print(json_data[1], json_data[0])
            m3u8_url_content = requests.get(url=json_data[1]).text
            print(m3u8_url_content)
            real_url = m3u8_url_content.split('\n')[2]
            m3u8_url = f'{scheme}://{m3u8_base_url}{real_url}'
            print(m3u8_url)
        fileSavePath = f'{base_dir}/{json_data[0]}'
        download_by_path_url(m3u8_url=m3u8_url, fileSavePath=fileSavePath)
        
if __name__ == "__main__":
    # get_single_page(1)
    # datas = batch_load_for_zhifou(73)
    # datas_json = json.dumps(datas)
    # print(datas_json)
    # open("zhifou_m3u8.json", mode="w+", encoding="utf-8").write(datas_json)
    # url = "https://vip1.lz-cdn.com/20220606/17432_0982c867/index.m3u8"
    # getTsFileInfo(url)
    # url = "https://vip1.lz-cdn.com/20220606/17432_0982c867/1000k/hls/mixed.m3u8"
    # getTsFileInfo(url)
    base_dir = "./知否知否，应是红肥绿瘦"
    # base_dir = "./我的阿勒泰"
    # m3u8_obj = m3u8.load(url)
    # total = len(m3u8_obj.segments)
    
    m3u8_url = "https://s3.bfengbf.com/video/wodealetai/%E7%AC%AC01%E9%9B%86/index.m3u8"
    # response = requests.get(url)
    # print(response.text)
    # download(m3u8_url, base_dir, 1)
    # download_and_merge(url, fileSavePath=fileSavePath)
    # bach_download(base_dir)
    # batch_merge_file(base_dir)
    # merge_mp4("D:\\workspace\\learning\\python-learning\\知否知否，应是红肥绿瘦\\第1集")
    m3u8_url = 'https://example.com/record/recordf/push-hw2.videocc.net/hls/7a118b4d061660476972854a1d3/2022-08-14-11-50-17_s.m3u8'
    fileSavePath = '11111'
    # download_single(m3u8_url, fileSavePath)
    # download_from_file(list_file_path="C:\\Users\\syske\\Downloads\\download_file_list.txt", file_base_dir='D:\\workspace\\learning\\python-learning\\video')
    batch_merge_file(filePath='D:\\workspace\\learning\\python-learning\\video')
    # merge_mp4("D:\\workspace\\learning\\python-learning\\知否知否，应是红肥绿瘦\\第31集")
    # 合并视频
    batch_merge_file_ignore_no_exist_file("D:\\workspace\\learning\\python-learning\\剑来")
    filePath = "D:\\workspace\\learning\\python-learning\\知否知否，应是红肥绿瘦\\第33集"
    # GetVideo.fileMerge(filePath=f'{filePath}', exculd_index=[199, 195, 196, 197, 198, 499,500, 501, 502, 503])
    # 获取下载地址
    # get_jianlai_donghua()
    # 下载视频
    # down_load_jianlai()
    # m3u8_url = get_m3u8_url(index_url='https://play.modujx16.com/20241127/VH7osgui/index.m3u8', target_url='1877kb/hls/index')
    # response = requests.get(url=m3u8_url)
    # print(response.text)

